//
//  DDTextView1.m
//  数据测试
//
//  Created by 肖棟棟 on 16/9/9.
//  Copyright © 2016年 肖棟棟. All rights reserved.
//

#import "DDTextView1.h"

#define WIDTH self.bounds.size.width
#define HEIGHT self.bounds.size.height

//网格虚线
#define xCount 5
#define yCount 4

//每个点之间x坐标的间距
#define baseWidth 37.5

#define gridBaseWidth baseWidth

//CGFloat gridBaseWidth = WIDTH/xCount;

#define KAraryCount 40

@interface DDTextView1(){
    //网格线
    CAShapeLayer *grid;
    //折线
    CAShapeLayer *snap;
    //最后一根横线
    //梯形
    CAShapeLayer *trape;
    //发光view的定时器
    NSTimer *timer;
}


@property (nonatomic, strong) UIBezierPath *linePath;
@property (nonatomic, strong) UIBezierPath *gridPath;
@property (nonatomic, strong) UIBezierPath *trapePath;


//记录当前要显示的第一个屏幕数组的数组对应的下表
@property (nonatomic, assign) int index;

//最后一个点(实际是数组倒数第二个点的动向坐标)
@property (nonatomic, assign) CGFloat lastPointX;
@property (nonatomic, assign) CGFloat lastPointY;

//滑动时 最右侧的
@property (nonatomic, assign) CGFloat lastWidth;

//最后2点的高度差
@property (nonatomic, assign) CGFloat heightCha;

//发光imegeView
@property (nonatomic, strong) UIImageView *lightView;
@property (nonatomic, strong) UIImageView *whiteView;

//右侧文本
@property (nonatomic, strong) UILabel *rightLb;




@end

@implementation DDTextView1


-(void)commit{
    //与网格相关
    grid = [CAShapeLayer layer];
    grid.lineWidth = 1;
    grid.strokeColor = [UIColor grayColor].CGColor;
    grid.fillColor = [UIColor clearColor].CGColor;
    //线条样式
    grid.lineDashPattern = @[@5,@3];
    [self.layer addSublayer:grid];
    
    //折线相关
    snap = [CAShapeLayer layer];
    snap.lineWidth = 2;
    snap.strokeColor = [UIColor orangeColor].CGColor;
    snap.fillColor = [UIColor clearColor].CGColor;
    [self.layer addSublayer:snap];
    
    //梯形图层
    trape = [CAShapeLayer layer];
    trape.lineWidth = 1;
    trape.strokeColor = [UIColor orangeColor].CGColor;
    trape.fillColor = [UIColor whiteColor].CGColor;
    [self.layer addSublayer:trape];
    
    
    //图片(黄色)
    UIImageView * lightView =[[UIImageView alloc] init];
    [self addSubview:lightView];
    lightView.frame = CGRectZero;
    self.backgroundColor =[UIColor blueColor];
    self.lightView = lightView;
    lightView.image =[UIImage imageNamed:@"yellowAlpha"];
    
    //图片(白色)
    UIImageView * whiteView =[[UIImageView alloc] init];
    [self addSubview:whiteView];
    whiteView.frame = CGRectZero;
    self.backgroundColor =[UIColor blueColor];
    self.whiteView = whiteView;
    whiteView.image =[UIImage imageNamed:@"whiteAlpha"];
    
    
    //开启定时器
    timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(lighting) userInfo:nil repeats:YES];
    [timer fire];
    
    //文本
    UILabel *rightLb =[[UILabel alloc] init];
    [self addSubview:rightLb];
    self.rightLb = rightLb;
    rightLb.font =[UIFont systemFontOfSize:8];
    rightLb.textColor =[UIColor blackColor];
    rightLb.textAlignment = NSTextAlignmentCenter;
    rightLb.backgroundColor =[UIColor clearColor];
    rightLb.frame = CGRectMake(self.lastPointX, self.lastPointY, 50, 20);
    
   
}

//定时器
-(void)lighting{
    if (self.lightView.alpha == 1) {
        [UIView animateWithDuration:0.5 animations:^{
            self.lightView.alpha = 0;
        }];
        
    }else {
        [UIView animateWithDuration:0.5 animations:^{
            self.lightView.alpha = 1;
        }];
    }
    
}

- (id)init{
    if ((self = [super init])) {
        [self commit];
    }
    return self;
}

-(void)awakeFromNib{
    [self commit];
}


- (void)drawRect:(CGRect)rect {
//    CGPoint point=self.contentOffset;
    //当前的index
    NSLog(@"当前的index= %d",self.index);
    
    
    //动画线(最后一个点)
    self.lastPointX = baseWidth * (self.yAxisLbArr.count + self.index -1);
    self.lastPointY = [self yPositionWithyValue:self.yAxisLbArr[self.yAxisLbArr.count -1]];
    
//    NSLog(@"传进来的数组%@",self.yAxisLbArr);
//    NSLog(@"最后一个点坐标%f,%f",self.lastPointX,self.lastPointY);
    
    //高度差
    self.heightCha = [self yPositionWithyValue:self.yAxisLbArr[self.yAxisLbArr.count -1]] -[self yPositionWithyValue:self.yAxisLbArr[self.yAxisLbArr.count -2]];
    
    //绘制网格线
    [self creatGrid];
    //绘制折线
    [self creatLine];
  
   
}

//绘制折线
-(void)creatLine{
    
    //重新画图
    CGPoint point=self.contentOffset;
//    NSLog(@"我曹,这个值有问题%@",NSStringFromCGPoint(point));
   
    //移除所有点
    [self.linePath removeAllPoints];
     self.linePath = nil;
     snap.path = nil;
    
    [self.trapePath removeAllPoints];
    self.trapePath = nil;
    trape.path = nil;
    
    //取整数
    self.index = point.x/baseWidth;
//    NSLog(@"当期的index%d",self.index);
    
    //当前对应点的x值
    CGFloat currentX=point.x;
//    NSLog(@"当期的对应点的值%f",currentX);
    self.lastWidth = currentX + WIDTH;
    //剩余的x值
//    CGFloat leftX = currentX - self.index * baseWidth;
//    NSLog(@"偏移量=%f",leftX);
    //计算点y值
    //self.index 对应的Y值
    NSNumber * num1 = self.yAxisLbArr[0];
    CGFloat firstPt =num1.intValue ;
//    NSLog(@"firstPt = %f",firstPt);
    
    //self.index+1 对应的Y值
    NSNumber * num2 = self.yAxisLbArr[1];
    CGFloat secondPt =num2.intValue ;
//    NSLog(@"secondPt = %f",secondPt);
    CGFloat kline = (secondPt-firstPt)/baseWidth;
//    NSLog(@"当前曲线值kline = %f",kline);
    
    //对应当前点的Y值
    CGFloat currentY = firstPt + kline * (currentX - self.index * baseWidth);
//    NSLog(@"当前点对应的x = %f,y =%f",currentX,currentY);
    
    [self.linePath moveToPoint:CGPointMake(currentX, currentY)];
    
    //此时应该从数组中的第一个元素开始绘图
    for (int i = 1; i< self.yAxisLbArr.count-1; i ++) {
        [self.linePath addLineToPoint:CGPointMake(baseWidth *(i+self.index), [self yPositionWithyValue:self.yAxisLbArr[i]])];
    }

    [self.linePath addLineToPoint:CGPointMake(self.lastPointX, self.lastPointY)];
    
    self.lightView.frame = CGRectMake(self.lastPointX-9, self.lastPointY-9, 18, 18);
    self.whiteView.frame = CGRectMake(self.lastPointX-5, self.lastPointY-5, 10, 10);
    //    最后2点动画
    [self.linePath addLineToPoint:CGPointMake(self.lastPointX, self.lastPointY)];
    //绘制最后一根线
    [self.linePath addLineToPoint:CGPointMake(self.lastWidth-50, self.lastPointY)];
    //最后梯形
    [self.trapePath moveToPoint:CGPointMake(self.lastWidth-50, self.lastPointY )];
    [self.trapePath addLineToPoint:CGPointMake(self.lastWidth, self.lastPointY)];
    [self.trapePath addLineToPoint:CGPointMake(self.lastWidth, self.lastPointY + 20)];
    [self.trapePath addLineToPoint:CGPointMake(self.lastWidth-40, self.lastPointY +20)];
    [self.trapePath addLineToPoint:CGPointMake(self.lastWidth-50, self.lastPointY)];
    
    //文本
    //定义属性字符串
    NSMutableString * aString =[NSMutableString stringWithFormat:@"%.3f",self.lastPointY];
    NSInteger  alength = aString.length;
    //设置attributes
    NSMutableAttributedString * aAttributedString = [[NSMutableAttributedString alloc] initWithString:aString];
    NSRange  rang1 =NSMakeRange(alength-3,3);
    [aAttributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:rang1];
    self.rightLb.attributedText  = aAttributedString;
    self.rightLb.frame = CGRectMake(self.lastWidth-50, self.lastPointY, 50, 20);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.016 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.lastPointX+=baseWidth/50.0;
        self.lastPointY+=self.heightCha/50.0;
        if (self.lastPointX<= baseWidth *(self.yAxisLbArr.count-1)) {
            [self creatLine];
        }
        
    });
   
    snap.path = self.linePath.CGPath;
//    trape.path = self.trapePath.CGPath;

}

-(void)creatGrid{

    //首先移除所有网格线
    //移除所有点
    [self.gridPath removeAllPoints];
    self.gridPath = nil;
    grid.path = nil;
    
    CGPoint point=self.contentOffset;
    //当前对应点的x值
    CGFloat currentX=point.x;
    CGFloat gridBaseHeight = HEIGHT/yCount;
    
    //TODO:绘制竖线(减少竖线数量)
    for (int i = 0; i<self.yAxisLbArr.count; i ++) {
        [self.gridPath moveToPoint:CGPointMake(baseWidth *(i+self.index ), 0)];
        [self.gridPath addLineToPoint:CGPointMake(baseWidth *(i+self.index) , HEIGHT)];
    }
    
    //绘制横线
    for (int i = 0; i<yCount; i ++) {
        [self.gridPath moveToPoint:CGPointMake(currentX, i*gridBaseHeight)];
        [self.gridPath addLineToPoint:CGPointMake(currentX+WIDTH , i*gridBaseHeight)];
    }

    grid.path = self.gridPath.CGPath;
}



#pragma mark - 懒加载
//线path
-(UIBezierPath *)linePath{
    if (_linePath == nil) {
        _linePath = [UIBezierPath bezierPath];
    }
    return _linePath;
}

-(UIBezierPath *)gridPath{
    if (_gridPath == nil) {
        _gridPath = [UIBezierPath bezierPath];
    }
    return _gridPath;
}

-(UIBezierPath *)trapePath{
    if (_trapePath == nil) {
        _trapePath = [UIBezierPath bezierPath];
    }
    return _trapePath;
}





//获取Y坐标
- (CGFloat)yPositionWithyValue:(NSNumber*)yValue{
    CGFloat y = [yValue floatValue];
    return y;
}



#pragma mark - 测试用的方法太乱
-(void)text{
    
    
    //GCD 子线程计算坐标,主线程更新UI
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //计算
        //最后一点和倒数第二个点
        //比如分5部分 (这段时间持续过程为1秒)
        int partOfTime = 5;
        //每一部分对应的X值
        CGFloat partX = baseWidth/partOfTime;
        //对应的Y值(高度差)
        CGFloat heightCha = [self yPositionWithyValue:self.yAxisLbArr.lastObject]-[self yPositionWithyValue:self.yAxisLbArr[self.yAxisLbArr.count-2]];
        CGFloat partY = heightCha/partOfTime;
        
        //最后一个点的横坐标
        CGFloat lastPointX = (self.index + self.yAxisLbArr.count-2)*baseWidth;
        //最后一个点Y坐标
        CGFloat lastPointY = (self.index + self.yAxisLbArr.count-2)*baseWidth;
        
        //计算出每一次的坐标
        for (int i = 0; i < partOfTime ; ++i) {
            [NSThread sleepForTimeInterval:1];
//            [self.linePath addLineToPoint:CGPointMake(lastPointX, currentY)];
//            NSLog(@"当前点的currentX = %f,currentY = %f",currentX,currentY);
            
            //主线程更新UI
            dispatch_sync(dispatch_get_main_queue(), ^{
                
                [NSThread sleepForTimeInterval:1];
                
                [self setNeedsDisplay];
                
            });
            
        }
        
    });
    
    
}


@end
